import java.net.*;
import java.io.*;
/*
 * UDPClient sends requests to server
 * and gets a reply, then update the cache
 */
public class UDPClient {
    private String hostName;
    private int serverPort = 2222;
    private byte[] buffer = new byte[1000]; 
	private String cache = "";//client side cache
    
    public UDPClient(String hostName) {
        this.hostName = hostName;
    }
    
    private void sendData(String msg) {
        DatagramSocket aSocket = null;
        try {
            aSocket = new DatagramSocket();//use free local port
            
            //Marshall data
            byte[] message = msg.getBytes();//buffer for sending
            
            //translate user-specified hostname to Internet address
            InetAddress aHost = InetAddress.getByName(hostName);
            DatagramPacket request = new DatagramPacket(message,message.length,aHost,serverPort);
            aSocket.send(request);//Send packet
            
            //Get reply after sending and update cache
            DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
            aSocket.receive(reply);
            System.out.println("Reply from Server: " + new String(reply.getData()));
        } catch (Exception e) {
            //Exceptions
        } finally {
            if(aSocket != null) {
                aSocket.close();
            }
        }
    }
    
    private void read(String filename) {
        //1. Check cache
        if(cache == "") {
           //2. if cache not available, access server
           String msg = "bla";
           sendData(msg);
        }
    }
    
    private void write(String filename,String content) {
        sendData(content);
    }
	
	private void monitor(String filename) {
		sendData(filename);
	}
}
